import React, { useState, useRef } from 'react';
import { Upload, X, File, CheckCircle, CloudUpload } from 'lucide-react';
import { Button } from '@/components/ui/button';

const UploadArea = ({ onClose }) => {
  const [dragActive, setDragActive] = useState(false);
  const [files, setFiles] = useState([]);
  const fileInputRef = useRef(null);

  const handleDrag = (e) => {
    e.preventDefault();
    e.stopPropagation();
    if (e.type === "dragenter" || e.type === "dragover") {
      setDragActive(true);
    } else if (e.type === "dragleave") {
      setDragActive(false);
    }
  };

  const handleDrop = (e) => {
    e.preventDefault();
    e.stopPropagation();
    setDragActive(false);
    
    if (e.dataTransfer.files && e.dataTransfer.files[0]) {
      handleFiles(e.dataTransfer.files);
    }
  };

  const handleChange = (e) => {
    e.preventDefault();
    if (e.target.files && e.target.files[0]) {
      handleFiles(e.target.files);
    }
  };

  const handleFiles = (fileList) => {
    const newFiles = Array.from(fileList).map((file, index) => ({
      id: Date.now() + index,
      file,
      name: file.name,
      size: formatFileSize(file.size),
      progress: 0,
      status: 'pending' // pending, uploading, completed, error
    }));
    
    setFiles(prev => [...prev, ...newFiles]);
    
    // 模拟上传过程
    newFiles.forEach(fileItem => {
      simulateUpload(fileItem.id);
    });
  };

  const simulateUpload = (fileId) => {
    const interval = setInterval(() => {
      setFiles(prev => prev.map(file => {
        if (file.id === fileId) {
          const newProgress = Math.min(file.progress + Math.random() * 30, 100);
          const newStatus = newProgress === 100 ? 'completed' : 'uploading';
          
          if (newProgress === 100) {
            clearInterval(interval);
          }
          
          return { ...file, progress: newProgress, status: newStatus };
        }
        return file;
      }));
    }, 200);
  };

  const formatFileSize = (bytes) => {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  const removeFile = (fileId) => {
    setFiles(prev => prev.filter(file => file.id !== fileId));
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-lg shadow-material-4 w-full max-w-2xl max-h-[80vh] overflow-hidden">
        {/* 头部 */}
        <div className="flex items-center justify-between p-6 border-b border-material-grey-200">
          <h2 className="text-xl font-semibold text-material-grey-800">
            上传文件
          </h2>
          <Button
            onClick={onClose}
            variant="ghost"
            size="icon"
            className="hover:bg-material-grey-100"
          >
            <X className="w-5 h-5 text-material-grey-500" />
          </Button>
        </div>

        {/* 上传区域 */}
        <div className="p-6">
          <div
            className={`border-2 border-dashed rounded-xl p-12 text-center transition-all duration-300 ${
              dragActive 
                ? 'border-primary bg-gradient-to-br from-primary/5 to-primary/10 scale-105' 
                : 'border-material-grey-300 hover:border-material-grey-400 hover:bg-material-grey-50'
            }`}
            onDragEnter={handleDrag}
            onDragLeave={handleDrag}
            onDragOver={handleDrag}
            onDrop={handleDrop}
          >
            <div className="flex flex-col items-center space-y-4">
              <div className={`p-4 rounded-full transition-all duration-300 ${
                dragActive 
                  ? 'bg-primary/20 scale-110' 
                  : 'bg-material-grey-100'
              }`}>
                <CloudUpload className={`w-12 h-12 transition-colors duration-300 ${
                  dragActive 
                    ? 'text-primary' 
                    : 'text-material-grey-400'
                }`} />
              </div>
              
              <div className="space-y-2">
                <h3 className="text-lg font-semibold text-material-grey-700">
                  {dragActive ? '释放文件开始上传' : '拖拽文件到此处上传'}
                </h3>
                <p className="text-material-grey-500">
                  支持多种文件格式，单个文件最大 100MB
                </p>
              </div>

              <input
                ref={fileInputRef}
                type="file"
                multiple
                onChange={handleChange}
                className="hidden"
              />
              
              <Button
                onClick={() => fileInputRef.current?.click()}
                className="bg-gradient-to-r from-primary to-primary-600 hover:from-primary-600 hover:to-primary-700 text-white shadow-material-2 hover:shadow-material-3 transition-all duration-200 transform hover:scale-105 active:scale-95"
                size="lg"
              >
                <Upload className="w-5 h-5 mr-2" />
                选择文件
              </Button>
            </div>
          </div>

          {/* 文件列表 */}
          {files.length > 0 && (
            <div className="mt-6">
              <h4 className="text-sm font-medium text-material-grey-700 mb-3">
                上传队列 ({files.length} 个文件)
              </h4>
              <div className="space-y-3 max-h-60 overflow-y-auto">
                {files.map((file) => (
                  <div key={file.id} className="flex items-center space-x-3 p-4 bg-material-grey-50 rounded-xl border border-material-grey-200 hover:shadow-material-1 transition-all duration-200">
                    <div className="p-2 bg-white rounded-lg shadow-sm">
                      <File className="w-5 h-5 text-material-grey-500 flex-shrink-0" />
                    </div>
                    
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center justify-between mb-2">
                        <p className="text-sm font-medium text-material-grey-800 truncate">
                          {file.name}
                        </p>
                        <span className="text-xs text-material-grey-500 bg-white px-2 py-1 rounded-full">
                          {file.size}
                        </span>
                      </div>
                      
                      {file.status === 'pending' && (
                        <div className="w-full bg-material-grey-200 rounded-full h-2">
                          <div className="bg-material-grey-300 h-2 rounded-full w-0 transition-all duration-300"></div>
                        </div>
                      )}
                      
                      {file.status === 'uploading' && (
                        <div className="w-full bg-material-grey-200 rounded-full h-2">
                          <div 
                            className="bg-gradient-to-r from-primary to-primary-600 h-2 rounded-full transition-all duration-300"
                            style={{ width: `${file.progress}%` }}
                          ></div>
                        </div>
                      )}
                      
                      {file.status === 'completed' && (
                        <div className="flex items-center space-x-2">
                          <CheckCircle className="w-4 h-4 text-green-500" />
                          <span className="text-xs text-green-600 font-medium">上传完成</span>
                        </div>
                      )}
                    </div>

                    <Button
                      onClick={() => removeFile(file.id)}
                      variant="ghost"
                      size="icon"
                      className="hover:bg-red-50 hover:text-red-600 flex-shrink-0"
                    >
                      <X className="w-4 h-4" />
                    </Button>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* 底部操作 */}
        <div className="flex items-center justify-end space-x-3 p-6 border-t border-material-grey-200 bg-material-grey-50">
          <Button
            onClick={onClose}
            variant="outline"
          >
            取消
          </Button>
          <Button
            onClick={onClose}
            className="bg-gradient-to-r from-primary to-primary-600 hover:from-primary-600 hover:to-primary-700"
            disabled={files.length === 0 || files.some(f => f.status === 'uploading')}
          >
            完成上传
          </Button>
        </div>
      </div>
    </div>
  );
};

export default UploadArea;
